const jwt = require('jsonwebtoken');


function sign(options,time){
    return jwt.sign(options,'66666' ,{
        expiresIn:time||'1day'//一天过期
    });
}
function verify(){
    return async(ctx,next)=>{
       const token=ctx.headers.authorization
       if(token){
        //检验合法
        try{
         const decoded=jwt.verify(token,'66666')
         if(decoded.id){//合法
            ctx.userId = decoded.id
           await next()
         }
        }catch(error){
             ctx.status = 401
            ctx.body={
                code:'0',
                msg:'登录失效'
            }

        }

       }else{
        ctx.status=401
        ctx.body={
            code:'0',
            msg:'请重新登录'
        }
       }
    }
}
function refreshVerify(token){
    try{
        const decoded=jwt.verify(token,'66666')
        if(decoded.id){//合法
            return decoded
        }
    }catch(error){
        return false
    }
}


module.exports={
    sign,
    verify,
    refreshVerify

}
